package com.car.comm;

import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DuplexMap<K,V> {
	class Entry{
		K k;
		V v;
		public Entry(K k,V v){
			this.k=k;
			this.v=v;
		}
		public K getK() {
			return k;
		}
		public V getV() {
			return v;
		}
		public void setK(K k) {
			this.k = k;
		}
		public void setV(V v) {
			this.v = v;
		}
	}
	private HashMap<K,Entry> kEntyMap=new HashMap<K,Entry>();
	private HashMap<V,Entry> vEntyMap=new HashMap<V,Entry>();
	private Lock mutexLock = new ReentrantLock();

	public boolean contains(K k){
		mutexLock.lock();
		boolean result = kEntyMap.containsKey(k);
		mutexLock.unlock();
		return result;
	}
	public boolean containsValue(V v){
		mutexLock.lock();
		boolean result = vEntyMap.containsKey(v);
		mutexLock.unlock();
		return result;
	}
	
	public V getByKey(K k){
		mutexLock.lock();
		Entry e=kEntyMap.get(k);
		if(e==null){
			mutexLock.unlock();
			return null;
		}
		mutexLock.unlock();
		return e.getV();
	}
	public K getbyValue(V v){
		mutexLock.lock();
		Entry e=vEntyMap.get(v);
		if(e==null){
			mutexLock.unlock();
			return null;
		}
		mutexLock.unlock();
		return e.getK();
	}
	public boolean put(K k,V v){
		if(k==null||v==null){
			return false;
		}
		mutexLock.lock();
		Entry e=new Entry(k, v);
		if(contains(k)){
			remove(k);
		}
		if(containsValue(v)){
			removeByValue(v);
		}
		kEntyMap.put(k, e);
		vEntyMap.put(v, e);
		mutexLock.unlock();
		return true;
	}
	public V remove(K k){
		mutexLock.lock();
		Entry e=kEntyMap.remove(k);
		if(e==null){
			mutexLock.unlock();
			return null;
		}
		vEntyMap.remove(e.getV());
		mutexLock.unlock();
		return e.getV();
	}
	public K removeByValue(V v){
		mutexLock.lock();
		Entry e=vEntyMap.remove(v);
		if(e==null){
			mutexLock.unlock();
			return null;
		}
		kEntyMap.remove(e.getK());
		mutexLock.unlock();
		return e.getK();
	}
	public void clear(){
		mutexLock.lock();
		kEntyMap.clear();
		vEntyMap.clear();
		mutexLock.unlock();
	}
}

